package com.bee.app.sms;

import java.util.Random;

import org.apache.log4j.Logger;

import com.jfinal.plugin.ehcache.CacheKit;

/**
 * 发送短信
 *
 * @author liuzy
 */
public class SmsManager {

	private static Logger logger = Logger.getLogger(SmsManager.class);

	/**
	 * 短信缓存名
	 */
	private static String SMS = "Sms";

	String smsModel = "小蜜蜂，嗡嗡嗡。您的短信验证码是%s，不要告诉别人哟。";

	/**
	 * 发送短信验证码
	 * 
	 * @param phoneNumber
	 * @return
	 */
	public static String send(String phoneNumber) {
		String verifyCode = randCode();
		// String content = String.format(smsModel, verifyCode);
		String smsId = new YtxSender().send(phoneNumber, verifyCode);
		CacheKit.put(SMS, smsId, verifyCode);
		return smsId;
	}

	/**
	 * 验证短信验证码
	 * 
	 * @param smsId
	 * @param verifyCode
	 * @return
	 */
	public static boolean validate(String smsId, String verifyCode) {
		if (verifyCode.equals(CacheKit.get(SMS, smsId))) {
			CacheKit.remove(SMS, smsId);
			return true;
		}
		return false;
	}

	private static String randCode() {
		final String number = "0123456789";
		StringBuilder code = new StringBuilder();
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			code.append(number.charAt(random.nextInt(10)));
		}
		logger.info("随机验证码:" + code);
		return code.toString();
	}

}
